package com.duck.duckchatbackend.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;

import com.duck.duckchatbackend.annotation.GlobalInterceptor;
import com.duck.duckchatbackend.entity.config.AppConfig;
import com.duck.duckchatbackend.entity.constans.Constants;
import com.duck.duckchatbackend.entity.dto.TokenUserInfoDto;
import com.duck.duckchatbackend.entity.enums.*;
import com.duck.duckchatbackend.entity.po.UserContact;
import com.duck.duckchatbackend.entity.po.UserInfoBeauty;
import com.duck.duckchatbackend.entity.query.UserContactQuery;
import com.duck.duckchatbackend.entity.vo.ResponseVO;
import com.duck.duckchatbackend.entity.vo.UserInfoVO;
import com.duck.duckchatbackend.exception.BusinessException;
import com.duck.duckchatbackend.mappers.UserInfoBeautyMapper;
import com.duck.duckchatbackend.redis.RedisComponent;

import com.duck.duckchatbackend.service.UserContactService;
import com.duck.duckchatbackend.utils.CopyTools;
import org.apache.catalina.User;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.duck.duckchatbackend.entity.query.UserInfoQuery;
import com.duck.duckchatbackend.entity.po.UserInfo;
import com.duck.duckchatbackend.entity.vo.PaginationResultVO;
import com.duck.duckchatbackend.entity.query.SimplePage;
import com.duck.duckchatbackend.mappers.UserInfoMapper;
import com.duck.duckchatbackend.service.UserInfoService;
import com.duck.duckchatbackend.utils.StringTools;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;


/**
 * 用户信息 业务接口实现
 */
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    private UserInfoMapper<UserInfo, UserInfoQuery> userInfoMapper;

    @Resource
    private UserInfoBeautyMapper<UserInfoBeauty, UserInfoQuery> userInfoBeautyMapper;

    @Resource
    private AppConfig appConfig;

    @Resource
    private RedisComponent redisComponet;

    @Resource
    private UserContactService userContactService;



    /**
     * 根据条件查询列表
     */
    @Override
    public List<UserInfo> findListByParam(UserInfoQuery param) {
        return this.userInfoMapper.selectList(param);
    }

    /**
     * 根据条件查询列表
     */
    @Override
    public Integer findCountByParam(UserInfoQuery param) {
        return this.userInfoMapper.selectCount(param);
    }

    /**
     * 分页查询方法
     */
    @Override
    public PaginationResultVO<UserInfo> findListByPage(UserInfoQuery param) {
        int count = this.findCountByParam(param);
        int pageSize = param.getPageSize() == null ? PageSize.SIZE15.getSize() : param.getPageSize();

        SimplePage page = new SimplePage(param.getPageNo(), count, pageSize);
        param.setSimplePage(page);
        List<UserInfo> list = this.findListByParam(param);
        PaginationResultVO<UserInfo> result = new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
        return result;
    }

    /**
     * 新增
     */
    @Override
    public Integer add(UserInfo bean) {
        return this.userInfoMapper.insert(bean);
    }

    /**
     * 批量新增
     */
    @Override
    public Integer addBatch(List<UserInfo> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userInfoMapper.insertBatch(listBean);
    }

    /**
     * 批量新增或者修改
     */
    @Override
    public Integer addOrUpdateBatch(List<UserInfo> listBean) {
        if (listBean == null || listBean.isEmpty()) {
            return 0;
        }
        return this.userInfoMapper.insertOrUpdateBatch(listBean);
    }

    /**
     * 多条件更新
     */
    @Override
    public Integer updateByParam(UserInfo bean, UserInfoQuery param) {
        StringTools.checkParam(param);
        return this.userInfoMapper.updateByParam(bean, param);
    }

    /**
     * 多条件删除
     */
    @Override
    public Integer deleteByParam(UserInfoQuery param) {
        StringTools.checkParam(param);
        return this.userInfoMapper.deleteByParam(param);
    }

    /**
     * 根据UserId获取对象
     */
    @Override
    public UserInfo getUserInfoByUserId(String userId) {
        return this.userInfoMapper.selectByUserId(userId);
    }

    /**
     * 根据UserId修改
     */
    @Override
    public Integer updateUserInfoByUserId(UserInfo bean, String userId) {
        return this.userInfoMapper.updateByUserId(bean, userId);
    }

    /**
     * 根据UserId删除
     */
    @Override
    public Integer deleteUserInfoByUserId(String userId) {
        return this.userInfoMapper.deleteByUserId(userId);
    }

    /**
     * 根据Email获取对象
     */
    @Override
    public UserInfo getUserInfoByEmail(String email) {
        return this.userInfoMapper.selectByEmail(email);
    }

    /**
     * 根据Email修改
     */
    @Override
    public Integer updateUserInfoByEmail(UserInfo bean, String email) {
        return this.userInfoMapper.updateByEmail(bean, email);
    }

    /**
     * 根据Email删除
     */
    @Override
    public Integer deleteUserInfoByEmail(String email) {
        return this.userInfoMapper.deleteByEmail(email);
    }

    /*
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(String email, String nickName, String password) {
        //根据邮箱查询改该邮箱是否已经注册过普通账号
        UserInfo userInfo = this.userInfoMapper.selectByEmail(email);
        if (null != userInfo) {
            throw new BusinessException("邮箱账号已经存在");
        }

        String userId;
        //根据邮箱查询改邮箱是否已经注册过靓号
        UserInfoBeauty beautyAccount = userInfoBeautyMapper.selectByEmail(email);
        //beautyAccount不为空且状态为未使用
        Boolean useBeautyAccount = null != beautyAccount && BeautyAccountStatusEnum.NO_USE.getStatus().equals(beautyAccount.getStatus());

        if (useBeautyAccount) {
            userId = UserContactTypeEnum.USER.getPrefix() + beautyAccount.getUserId();
        } else {
            userId = StringTools.getUserId();
        }
        Date curDate = new Date();
        userInfo = new UserInfo();
        userInfo.setUserId(userId);
        userInfo.setEmail(email);
        userInfo.setNickName(nickName);
        userInfo.setPassword(StringTools.encodeByMD5(password));
        userInfo.setCreateTime(curDate);
        userInfo.setStatus(UserStatusEnum.ENABLE.getStatus());
        userInfo.setLastOffTime(curDate.getTime());
        userInfo.setJoinType(JoinTypeEnum.APPLY.getType());
        this.userInfoMapper.insert(userInfo);
        //更新靓号状态
        if (useBeautyAccount) {
            UserInfoBeauty updateBeauty = new UserInfoBeauty();
            updateBeauty.setStatus(BeautyAccountStatusEnum.USEED.getStatus());
            this.userInfoBeautyMapper.updateById(updateBeauty, beautyAccount.getId());
        }

         //创建机器人好友
         userContactService.addContact4Robot(userId);
    }

    /**
     * 用户登录方法
     *
     * @param email    用户邮箱，用于识别用户身份
     * @param password 用户密码，用于验证用户身份
     * @return 登录成功后的用户信息和令牌信息
     * @throws BusinessException 当用户名或密码错误，或账号被禁用时抛出异常
     */
    @Override
    public UserInfoVO login(String email, String password) {
        // 通过邮箱查询用户信息
        UserInfo userInfo = this.userInfoMapper.selectByEmail(email);
        // 验证用户信息是否存在且密码正确
        if (null == userInfo || !password.equals(userInfo.getPassword())) {
            throw new BusinessException("账号或者密码错误");
        }
        // 检查用户账号状态，防止使用禁用账号登录
        if (UserStatusEnum.DISABLE.equals(userInfo.getStatus())) {
            throw new BusinessException("账号已禁用");
        }

        //TODO 查询群主
        UserContactQuery contactQuery = new UserContactQuery();
        contactQuery.setUserId(userInfo.getUserId());
        contactQuery.setStatus(UserContactStatusEnum.FRIEND.getStatus());
        List<UserContact> contactList = userContactService.findListByParam(contactQuery);
        List<String> contactIdList = contactList.stream().map(item -> item.getContactId()).collect(Collectors.toList());
        //存放到redis中
        redisComponet.cleanUserContact(userInfo.getUserId());
        if (contactIdList.isEmpty()) {
            redisComponet.addUserContactBatch(userInfo.getUserId(), contactIdList);
        }
        //TODO 查询我的联系人

        // 获取用户令牌信息并返回
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfoDto(userInfo);
        Long lastHeartBeat = redisComponet.getUserHeartBeat(userInfo.getUserId());
        if (null != lastHeartBeat) {
            throw new BusinessException("此账号已经在别处登录，请退出后在登录");
        }
        // 保存登录信息到redis中
        String token = StringTools.encodeByMD5(tokenUserInfoDto.getUserId() + StringTools.getRandomString(Constants.LENGTH_20));
        tokenUserInfoDto.setToken(token);
        redisComponet.saveTokenUserInfoDto(tokenUserInfoDto);

        UserInfoVO userInfoVO = CopyTools.copy(userInfo, UserInfoVO.class);
        userInfoVO.setToken(tokenUserInfoDto.getToken());
        userInfoVO.setAdmin(tokenUserInfoDto.getAdmin());
        return userInfoVO;
    }


    /**
     * 构建用户令牌信息方法
     *
     * @param userInfo 用户信息，用于构建令牌信息
     * @return 用户令牌信息对象
     */
    private TokenUserInfoDto getTokenUserInfoDto(UserInfo userInfo) {
        TokenUserInfoDto tokenUserInfo = new TokenUserInfoDto();
        tokenUserInfo.setUserId(userInfo.getUserId());
        tokenUserInfo.setNickName(userInfo.getNickName());
        // 检查用户是否为管理员
        String adminEmails = appConfig.getAdminEmails();
        if (!StringUtils.isEmpty(adminEmails) && ArrayUtils.contains(adminEmails.split(","), userInfo.getEmail())) {
            tokenUserInfo.setAdmin(true);
        } else {
            tokenUserInfo.setAdmin(false);
        }
        return tokenUserInfo;
    }

    /**
     * 更新用户信息的方法
     * 该方法处理用户信息的更新，包括用户昵称和头像
     * 如果提供了头像文件，方法将首先保存头像，然后更新数据库中的用户信息
     * 该方法注解为事务性操作，确保在出现异常时回滚更改
     *
     * @param userInfo    用户信息对象，包含要更新的用户数据
     * @param avatarFile  用户头像文件
     * @param avatarCover 用户头像封面文件
     * @throws IOException 如果文件保存过程中发生I/O错误
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfo(UserInfo userInfo, MultipartFile avatarFile, MultipartFile avatarCover) throws IOException {
        // 检查是否提供了头像文件
        if (avatarFile != null) {
            // 获取基础文件夹路径
            String baseFolder = appConfig.getProjectFolder() + Constants.FILE_FOLDER_FILE;
            // 构建目标文件夹路径
            File targetFileFolder = new File(baseFolder + Constants.FILE_FOLDER_AVATAR_NAME);
            // 如果目标文件夹不存在，则创建
            if (!targetFileFolder.exists()) {
                targetFileFolder.mkdirs();
            }
            // 构建文件路径
            String filePath = targetFileFolder.getPath() + "/" + userInfo.getUserId() + Constants.IMAGE_SUFFIX;
            // 保存头像文件和头像封面文件
            avatarFile.transferTo(new File(filePath));
            avatarCover.transferTo(new File(filePath + Constants.COVER_IMAGE_SUFFIX));
        }

        // 先查询数据库中的用户信息，以防止行锁
        UserInfo dbInfo = this.userInfoMapper.selectByUserId(userInfo.getUserId());

        // 更新数据库中的用户信息
        this.userInfoMapper.updateByUserId(userInfo, userInfo.getUserId());

        // 初始化昵称更新变量
        String contactNameUpdate = null;
        // 检查昵称是否更改，如果未更改，则设置昵称为更新会话信息中的昵称
        if (dbInfo.getNickName().equals(userInfo.getNickName())) {
            contactNameUpdate = userInfo.getNickName();
        }

        // TODO: 更新会话信息中的昵称信息
       // userContactService.
        //userContactService.add();
    }

    @Override
    public void updateUserStatus(Integer status, String userId) {
        UserStatusEnum userStatusEnum = UserStatusEnum.getByStatus(status);
        if (userStatusEnum == null) {
            throw new BusinessException("状态值错误");
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setStatus(userStatusEnum.getStatus());
        this.userInfoMapper.updateByUserId(userInfo, userId);
    }

    @Override
    public void forceOffLine(@NotEmpty String userId) {
        //TODO 强制下线

    }
}